﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Lister;

namespace COFE.Core.Utils
{


    public static class FactoryRegister<T>
    {
        #region Static Methods



        public static void RegisterFactory(string factorykey, IFactory<T> factory)
        {
            if (!_factories.ContainsKey(factorykey))
                _factories.Add(factorykey, factory);
        }

        public static void RegisterFactory(IFactory<T> factory)
        {
            RegisterFactory(factory.FactoryKey, factory);
        }

        public static string FindFactory(IFactory<T> factory)
        {
            foreach (var f in _factories)
                if (f.Value.Equals(factory))
                    return f.Key;
            return null;
        }

        public static IFactory<T> FindFactory(string factoryKey)
        {
            foreach (var f in _factories)
                if (f.Key == factoryKey)
                    return f.Value;
            return null;
        }

        public static void RegisterFactory(string factoryKey, 
            Func<string, string, T> constructMethod, Func<T, string> recycleMethod = null)
        {
            RegisterFactory(factoryKey, new DelegateFactory<T>(factoryKey, constructMethod, recycleMethod));
        }

        //public static void RegisterFactory(string factoryKey,
        //    string separator,
        //    Func<string, string, T> constructMethod, Func<T, string> recycleMethod = null)
        //{
        //    RegisterFactory(factoryKey,
        //        (key, param) => constructMethod(key, String.Join(separator, param)),
        //        (product) => 
        //            recycleMethod == null ? null : 
        //            recycleMethod(product).Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries));            
        //}


        #endregion

        #region Data

        static Dictionary<string, IFactory<T>> _factories = new Dictionary<string, IFactory<T>>();

        #endregion

        #region Public Properties

        public static Dictionary<string, IFactory<T>> Factories { get { return _factories; } }

        #endregion
    }
}
